package com.bawei.mall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.domain.MallProductSkuInfo;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.mall.user.domain.MallCusProductCar;
import com.bawei.mall.user.domain.MallProductEntity;
import com.bawei.mall.user.mapper.MallCusProductCarMapper;
import com.bawei.mall.user.service.IMallCusProductCarService;
import com.bawei.system.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：HaoYunde
 * @Package：com.bawei.mall.user.service
 * @Project：mall_cloud
 * @name：MallCusProductCarServiceImpl
 * @Date：2024/7/5 14:53
 */
@Service
public class MallCusProductCarServiceImpl extends ServiceImpl<MallCusProductCarMapper, MallCusProductCar> implements IMallCusProductCarService {
    @Autowired
    private MallCusProductCarMapper carMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String ACCESS_TOKEN="login_tokens:";


    /**
     * 添加购物车
     * @param mallCusProductCar
     */
    @Override
    public void create(MallCusProductCar mallCusProductCar) {
        Integer userId = getCurrentUserId();
        mallCusProductCar.setUserId(userId.longValue());
        carMapper.insert(mallCusProductCar);
    }

    /**
     * 查询购物车
     * @return
     */
    @Override
    public List<MallProductEntity> findCarList() {
        // 获取当前登录用户的ID
        Integer userId = getCurrentUserId();

//        QueryWrapper<MallCusProductCar> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(MallCusProductCar::getUserId, userId);
//        List<MallCusProductCar> list = carMapper.selectList(queryWrapper);
        List<MallProductEntity> list=carMapper.findListByUserId(userId);
        for (MallProductEntity mallProductEntity : list) {
            String sku = mallProductEntity.getProductAttr();
            String[] split = sku.split(",");
            List<Map> type=new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                Map map = new HashMap<>();
                map.put("key",i+1);
                map.put("value",split[i]);
                type.add(map);
            }
            mallProductEntity.setProductAttr(JSON.toJSONString(type));
        }
        return list;
    }

    /**
     * 清空购物车
     */

    @Override
    public void deleteAllCar() {
        // 获取当前登录用户的ID
        Integer userId = getCurrentUserId();
        carMapper.deleteAllCar(userId);
    }

    /**
     * 删除购物车
     * @param id
     */
    @Override
    public void delete(Long id) {
        carMapper.deleteById(id);
    }

    /**
     * 更新购物车
     * @param id
     * @param quantity
     */
    @Override
    public void updateQuantity(Long id, Integer quantity) {
        carMapper.updateQuantity(id,quantity);
    }

    /**
     * 获取当前登录用户的ID
     * @return 用户ID
     */
    private Integer getCurrentUserId() {
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String o = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSON.parseObject(o, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        return cusUser.getUserId();
    }


    private String getTokenKey(String key)
    {
        return ACCESS_TOKEN + key;
    }
}
